package httputils

import (
	"crypto/tls"
	"encoding/json"
	"io/ioutil"
	"net"
	"net/http"
	"net/http/cookiejar"
	"time"
)

var HttpClient *http.Client

func GetHttpClient() *http.Client {
	if nil != HttpClient {
		return HttpClient
	}
	tr := &http.Transport{ //跳过https请求的证书验证
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	cookieJar, _ := cookiejar.New(nil) //http cookie接口
	HttpClient = &http.Client{
		Jar:       cookieJar,
		Transport: tr,
	}
	return HttpClient
}

func DoRequest(request *http.Request) (*http.Response, error) {
	return GetHttpClient().Do(request)
}

func RequestBody(r *http.Request) string {
	b, _ := ioutil.ReadAll(r.Body)
	param := string(b)
	return param
}

func RequestBodyStruct(r *http.Request, v interface{}) {
	b, _ := ioutil.ReadAll(r.Body)
	json.Unmarshal(b, &v)
}

func ResponseJson(r http.ResponseWriter, code int, msg string, data interface{}, err error) {
	r.Header().Add("Content-Type", "application/json")
	var result JsonBody
	if err != nil {
		result = JsonBody{Code: code, Message: err.Error(), Data: err}
	} else {
		result = JsonBody{Code: code}
		if len(msg) > 0 {
			result.Message = msg
		}
		if data != nil {
			result.Data = data
		}
	}
	bytes, _ := json.Marshal(result)
	r.Write(bytes)
}

func ResponseJsonSuccess(r http.ResponseWriter, code int, msg string, data interface{}) {
	ResponseJson(r, code, msg, data, nil)
}

func ResponseJsonError(r http.ResponseWriter, code int, err error) {
	ResponseJson(r, code, err.Error(), nil, err)
}

type JsonBody struct {
	Code    int         `json:"code"`
	Message string      `json:"msg"`
	Data    interface{} `json:"data"`
}

func PortScan(host, port string) bool {
	_, err := net.DialTimeout("tcp", host+":"+port, time.Second*3)
	return err == nil
}
